package sardine.server;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import sardine.SardineBase;
import sardine.asset.AssetsHandler;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import static io.netty.handler.codec.http.HttpResponseStatus.OK;

/**
 * @auth bruce_sha
 * @date 2015/6/11
 */
@ChannelHandler.Sharable
public class SardineInboundHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    final MatcherProcessor filter;

    public SardineInboundHandler(MatcherProcessor filter) {
        this.filter = filter;
    }

   int count=0;

    protected void messageReceived(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {

        final FullHttpResponse response = new DefaultFullHttpResponse(request.protocolVersion(), OK);

        {//TODO
            String clientIP = request.headers().getAndConvert("X-Forwarded-For");
            if (clientIP == null) {
                InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
                clientIP = insocket.getAddress().getHostAddress();
            }
            request.headers().set("X-SARDINE-IP", clientIP);
        }
        try {
            // build the request so 'getInputStream()' can be called multiple times
            filter.process(request, response, ctx);
//            baseRequest.setHandled(true);
        } catch (NotConsumedException ignore) {
            try {
                if (!AssetsHandler.handleResource(request, ctx)) {
                    // TODO : Not use an exception in order to be faster.
//            baseRequest.setHandled(false);
                    //TODO:注意这里有问题，到底先处理静态文件还是动态文件
                    response.setStatus(HttpResponseStatus.NOT_FOUND);
                    response.content().writeBytes(SardineBase.NOT_FOUND.getBytes(StandardCharsets.UTF_8));
                    response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
                    ctx.writeAndFlush(response);
                }
//            if (StaticResourceHanlder.handle2 (ctx, request))     return;
            } catch (Exception e) {
                //ignore
            }
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        super.channelReadComplete(ctx);
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        ctx.close();
    }

}